
// Cellular noise ("Worley noise") in 3D in GLSL.
// Copyright (c) Stefan Gustavson 2011-04-19. All rights reserved.
// This code is released under the conditions of the MIT license.
// See LICENSE file for details.
// https://github.com/stegu/webgl-noise

// Cellular noise, returning F1 and F2 in a vec2.
// Speeded up by using 2x2x2 search window instead of 3x3x3,
// at the expense of some pattern artifacts.
// F2 is often wrong and has sharp discontinuities.
// If you need a good F2, use the slower 3x3x3 version.
vec2 cellular2x2x2(vec3 P) {

	vec3 Pi = mod289( floor( P ) );
 	vec3 Pf = fract( P );
	vec4 Pfx = Pf.x + vec4( 0.0, -1.0, 0.0, -1.0 );
	vec4 Pfy = Pf.y + vec4( 0.0, 0.0, -1.0, -1.0 );
	vec4 p = permute( Pi.x + vec4( 0.0, 1.0, 0.0, 1.0 ) );
	p = permute( p + Pi.y + vec4( 0.0, 0.0, 1.0, 1.0 ) );
	vec4 p1 = permute( p + Pi.z ); // z+0
	vec4 p2 = permute( p + Pi.z + vec4( 1.0 ) ); // z+1
	vec4 ox1 = fract( p1 * K ) - Ko;
	vec4 oy1 = mod7( floor( p1 * K ) ) * K - Ko;
	vec4 oz1 = floor( p1 * K2 ) * Kz - Kzo; // p1 < 289 guaranteed
	vec4 ox2 = fract( p2 * K ) - Ko;
	vec4 oy2 = mod7( floor( p2 * K ) ) * K - Ko;
	vec4 oz2 = floor( p2 * K2 ) * Kz - Kzo;
	vec4 dx1 = Pfx + jitter1 * ox1;
	vec4 dy1 = Pfy + jitter1 * oy1;
	vec4 dz1 = Pf.z + jitter1 * oz1;
	vec4 dx2 = Pfx + jitter1 * ox2;
	vec4 dy2 = Pfy + jitter1 * oy2;
	vec4 dz2 = Pf.z - 1.0 + jitter1 * oz2;
	vec4 d1 = dx1 * dx1 + dy1 * dy1 + dz1 * dz1; // z+0
	vec4 d2 = dx2 * dx2 + dy2 * dy2 + dz2 * dz2; // z+1

	// Do it right and sort out both F1 and F2
	vec4 d = min( d1, d2 ); // F1 is now in d
	d2 = max( d1, d2 ); // Make sure we keep all candidates for F2
	d.xy = ( d.x < d.y ) ? d.xy : d.yx; // Swap smallest to d.x
	d.xz = ( d.x < d.z ) ? d.xz : d.zx;
	d.xw = ( d.x < d.w ) ? d.xw : d.wx; // F1 is now in d.x
	d.yzw = min( d.yzw, d2.yzw ); // F2 now not in d2.yzw
	d.y = min( d.y, d.z ); // nor in d.z
	d.y = min( d.y, d.w ); // nor in d.w
	d.y = min( d.y, d2.x ); // F2 is now in d.y
	return sqrt( d.xy ); // F1 and F2

}
